package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCargoPublishCargoInfoBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.self.GoodsSelectEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.widget.ClearEditText;
import com.sgb.kjwl.view.widget.transport.GoodsTypeChooseDialog;
import com.sgb.kjwl.viewmodel.transport.CargoPublishCargoInfoViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 2020/12/29 17:50
 * @Description: 货源发布填写货物信息页面
 */
public class CargoPublishCargoInfoActivity extends AppActivity implements GoodsTypeChooseDialog.CallBack {

    @Inject
    CargoPublishCargoInfoViewModel viewModel;
    ActivityCargoPublishCargoInfoBinding binding;
    //选择弹窗
    private OptionsPickerView<GoodsInfoTypeEntity3> mModePicker;
    private OptionsPickerView<GoodsSelectEntity> mPackagePicker;
    //数据实体类
    private CargoPublishEntity mEntity;
    //上次选择的货源no
    private String mOldGoodsModeNo;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, CargoPublishCargoInfoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_cargo_publish_cargo_info);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("货物信息");
        initEvent();
        initData();
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        //设置输入范围，失去焦点后自动补全
        binding.etReleaseCargoWeight.setOnFocusChangeListener(new RangeFocusChangeListener(0.01, 999.99) {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                super.onFocusChange(v, hasFocus);
                addEtPrefix(hasFocus, binding.etReleaseCargoWeight);
            }
        });
        binding.etReleaseCargoVolume.setOnFocusChangeListener(new RangeFocusChangeListener(0.01, 999.99) {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                super.onFocusChange(v, hasFocus);
                addEtPrefix(hasFocus, binding.etReleaseCargoVolume);
            }
        });
        //接口监听
        viewModel.ldMode.observe(this, this::syncGoodsMode);
        viewModel.ldPackage.observe(this, this::syncPackageMode);
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        } else {
            syncData();
        }
        //获取货物类型和包装方式
        viewModel.getGoodsMode(this);
        viewModel.getPackageMode(this);
    }

    private void syncData() {
        //设置上次选择货源的no
        if (mEntity.getGoodsModeNo() != null) {
            mOldGoodsModeNo = mEntity.getGoodsModeNo();
        }
        if (!TextUtils.isEmpty(mEntity.getGoodsModeName())) {
            binding.tvReleaseCargoType.setText(mEntity.getGoodsModeName());
        }
        if (!TextUtils.isEmpty(mEntity.getPackageModeName())) {
            binding.tvReleaseCargoPackage.setText(mEntity.getPackageModeName());
        }
        if (mEntity.getGoodsWeight() != 0) {
            binding.etReleaseCargoWeight.setText(String.format("约%s", NumberUtil.trim0(mEntity.getGoodsWeight())));
        }
        if (mEntity.getGoodsVolume() != 0) {
            binding.etReleaseCargoVolume.setText(String.format("约%s", NumberUtil.trim0(mEntity.getGoodsVolume())));
        }
    }

    /**
     * 添加前缀
     */
    private void addEtPrefix(boolean hasFocus, ClearEditText editText) {
        Editable editable = editText.getText();
        //有焦点时移除前缀
        if (hasFocus) {
            if (editable != null && editable.toString().startsWith("约")) {
                editText.setText(editable.toString().substring(1));
            }
            return;
        }
        //失去焦点时添加前缀
        if (editable != null && editable.length() > 0 && !editable.toString().startsWith("约")) {
            editText.setText(String.format("约%s", editable));
        }
    }

    /**
     * 设置货物类型数据
     */
    private void syncGoodsMode(List<GoodsInfoTypeEntity3> list) {
        mModePicker = PickerHelper.with(this).getCommonPicker("选择货物类型", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setGoodsModeNo(entity.getNo());
            mEntity.setGoodsModeName(entity.getName());
            //设置回显
            binding.tvReleaseCargoType.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 设置包装方式数据
     */
    private void syncPackageMode(List<GoodsSelectEntity> list) {
        mPackagePicker = PickerHelper.with(this).getCommonPicker("选择包装方式", list, (options1, options2, options3, v) -> {
            GoodsSelectEntity entity = list.get(options1);
            //设置数据
            mEntity.setPackageModeNo(entity.getNo());
            mEntity.setPackageModeName(entity.getName());
            //设置回显
            binding.tvReleaseCargoPackage.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    GoodsTypeChooseDialog goodsTypeDialog;

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.llReleaseCargoType) {
            if (goodsTypeDialog == null) {
                goodsTypeDialog = GoodsTypeChooseDialog.newInstance((ArrayList<GoodsInfoTypeEntity3>) viewModel.ldMode.getValue()).callBack(this);
            }
            goodsTypeDialog.show(getSupportFragmentManager(),"top");
        } else if (v == binding.llReleaseCargoPackage) {
            if (mPackagePicker != null) {
                mPackagePicker.show();
            }
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }
    }

    /**
     * 货物类型回调
     */
    @Override
    public void select(GoodsInfoTypeEntity3 entity) {
        if (entity == null) return;
        //设置数据
        if (TextUtils.isEmpty(entity.getParentNo())) {
            mEntity.setGoodsModeNo(entity.getNo());
            mEntity.setGoodsModeName(entity.getName());
        } else {
            mEntity.setGoodsModeNo(entity.getParentNo());
            mEntity.setGoodsModeName(entity.getName());
            mEntity.setSecondGoodsTypeNo(entity.getNo());
        }
        String name = entity.getName();
        if (name.contains("/")) {
            name = name.substring(name.indexOf("/") + 1);
        }
        //设置回显
        binding.tvReleaseCargoType.setText(DefaultUtil.getString(name));
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        if (TextUtils.isEmpty(mEntity.getGoodsModeName())) {
            MToast.showToast(this, "请选择货物类型");
            return;
        }
        if (TextUtils.isEmpty(mEntity.getPackageModeName())) {
            MToast.showToast(this, "请选择包装方式");
            return;
        }
        String weight = binding.etReleaseCargoWeight.getText().toString();
        //判断是否填写货重
        if (TextUtils.isEmpty(weight)) {
            MToast.showToast(this, "请先填写货物重量");
            return;
        }
        //设置货重
        if (!TextUtils.isEmpty(weight)) {
            weight = weight.startsWith("约") ? weight.substring(1) : weight;
            mEntity.setGoodsWeight(NumberUtil.convertToDouble(weight));
        } else {
            mEntity.setGoodsWeight(0);
        }
        String volume = binding.etReleaseCargoVolume.getText().toString();
        //设置体积
        if (!TextUtils.isEmpty(volume)) {
            volume = volume.startsWith("约") ? volume.substring(1) : volume;
            mEntity.setGoodsVolume(NumberUtil.convertToDouble(volume));
        } else {
            mEntity.setGoodsVolume(0);
        }
        //判断是否修改了货源信息
        if (mOldGoodsModeNo != null && !mOldGoodsModeNo.equals(mEntity.getGoodsModeNo())
                && (mEntity.getCarLenList() != null || mEntity.getCarTypeList() != null)) {
            //修改了货物类型且填写过车辆信息则清空车辆信息，并提示
            showTipDialog();
        } else {
            finishWithData();
        }
    }

    private void finishWithData() {
        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 提示弹窗
     */
    private void showTipDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("您已填写车辆要求，货物类型与车型具有关联性，确定修改货物类型将会清空车辆要求，是否确定修改？")
                .confirmCallback(v -> {
                    mEntity.setCarTypeList(null);
                    mEntity.setCarLenList(null);
                    mEntity.setHeightHurdle(0);
                    mEntity.setIsDump(null);
                    finishWithData();
                })
                .show();
    }
}
